<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t("basic_information") }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            :list-type-info="listTypeInfo"
          >
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>挂网信息</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.spreadRef"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.spreadFieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            :list-type-info="listTypeInfo"
          >
            <template v-slot:form-networkProductType>
              <el-select
                clearable
                v-model="formInfo.data.networkProductType"
              >
                <el-option
                  :value="item.code"
                  v-for="(item, index) in networkProductTypeList"
                  :key="index"
                  :label="item.name"
                />
              </el-select>
            </template>
            <template v-slot:form-networkUnitCoefficient>
              <el-input
                    style="width: 60px"
                    type="input"
                    placeholder=""
                    v-model="formInfo.data.systemUnitCoefficient"
                  >
                  </el-input>  
                {{ unitvalue }}
                <el-tooltip placement="top" effect="light" content="系统单位">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                =
                <el-input
                  style="width: 60px"
                  type="input"
                  placeholder=""
                  v-model="formInfo.data.networkUnitCoefficient"
                >
                </el-input>
                {{ formInfo.data.networkUnit }}
                <el-tooltip placement="top" effect="light" content="挂网单位">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </template>
            <template v-slot:form-networkPrice>
                <el-input
                  type="input"
                  placeholder="请输入"
                  :disabled="true"
                  v-model="formInfo.data.networkPrice"
                >
                  <template #append>
                    {{
                      formInfo.data.networkUnit
                        ? '元/' + formInfo.data.networkUnit
                        : '-'
                    }}
                  </template>
                </el-input>
              </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
          <div class="model-panel-title">
            <p>供应商信息</p>
          </div>
          <div class="model-panel-body">
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addSuppler>
                <el-button
                  v-if="$permission('product:relationSupplier')"
                  @click="addSuppler"
                  >添加供应商</el-button
                >
              </template>
              <template v-slot:filter-remove>
                <el-button
                  :disabled="!tableInfo.selections.length"
                  v-if="$permission('product:relationSupplierDel')"
                  @click="remove"
                  >删除供应商</el-button
                >
              </template>
            </page-filter>
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <page-table
                v-model:data.sync="tableInfo.data"
                :pager="false"
                :check-box="true"
                :tabIndex="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-supplierName="scope">
                  <p class="slip-edit" @click="showSupplier(scope.row)">
                    {{ scope.row.supplierName || '-' }}
                  </p>
                </template>
                <template v-slot:col-price="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}[price]`"
                    :rules="
                      scope.$index >= 0
                        ? {
                            validator: $validate.positiveMoneyZero,
                            trigger: 'blur',
                          }
                        : {}
                    "
                  >
                    <el-input-number
                      v-model="scope.row.price"
                      controls-position="right"
                      style="minwidth: 100%; margintop: 18px"
                      :precision="
                        $store.state.permission.systemConfig.price_precision
                      "
                      :step="1"
                      :min="0"
                      :disabled="id && !isCopy ? true : false"
                      :max="999999999999999"
                      @change="
                        changePrice($event, `data.${scope.$index}.price`)
                      "
                    />
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
    </NewFullScreen>
    <SelectSupplierAddPrice
      v-if="supplierInfo.visible && id && !isCopy"
      v-model:show-dialog="supplierInfo.visible"
      :query="supplierInfo.query"
      :check-box="true"
      :highlight-row="false"
      :api="supplierInfo.api"
      @callback="supplierCallback"
    />
    <SelectSupplier
      v-if="supplierInfo.visible && (!id || isCopy)"
      v-model:show-dialog="supplierInfo.visible"
      :query="supplierInfo.query"
      :check-box="true"
      :highlight-row="false"
      :api="supplierInfo.api"
      @callback="supplierCallback"
    />
  </div>
</template>

<script setup name="productDrugModify">
import utils from "@/common/js/utils"; // 公共方法

import PageForm from "@/components/PageForm/index";
import { getDrugById, updateDrug } from "@/api/core";
import { getCoreCodeStatus } from "@/api/core";
import axios from "axios";
import SelectSettingClassification from "@/components/SelectSettingClassification/index";
import SelectSupplier from '@/components/SelectSupplier/index'
import SelectSupplierAddPrice from '@/components/SelectSupplier/SelectSupplierAddPrice'
import { getUnitAll , getSupplierPage, getSupplierProductAll,   productsRelationSupplier,
  productsRelationSupplierDel,setSupplierProductDefault} from "@/api/core";

const { proxy } = getCurrentInstance();
const emits = defineEmits();
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
    default: "",
  },
  title: {
    type: String,
    default: "",
  },
  isCopy: {
    type: Boolean,
    default: false
  },
});
let checkFrequency = (rule, value, callback) => {
  let minutes = formInfo.value.data.systemUnitCoefficient;
  console.log(minutes, value)
  if (!value || !minutes) {
    callback(new Error('请输入单位比例'));
  }
  callback();
}
const filterInfo = ref({
  query: {
    productId: props.id,
    sort: 'is_default desc,create_time desc',
  },
  list: [
    { type: 'slot', value: 'addSuppler' },
    { type: 'slot', value: 'remove' },
  ],
})
const tableInfo = ref({
  data: [],
  selections: [],
  fieldList: [
    { label: '供应商名称', value: 'supplierName' },
    { label: '供应商编码', value: 'supplierCode' },
    {
      label: '供应商价格',
      value: 'price',
      type: 'slot',
      width: '220px',
    },
    { label: '是否默认', value: 'isDefaultValue' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '110',
    btList: [
      {
        label: '设为默认',
        event: setDefault,
        show: true,
        ifRender: function (row) {
          return row.isDefault !== 1
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('azDrug:delete'),
      },
    ],
  },
})
const supplierInfo = ref({
  visible: false,
  api: getSupplierPage,
  query: {
    status: 1,
    searchType: 'org',
    searchField: 'supplierId',
    sort: 'create_time desc,id asc',
    supplierIdNotIn: '',
  },
})
const formInfo = ref({
  ref: null,
  spreadRef: null,
  data: {
    systemUnitCoefficient:''
  },
  fieldList: [
    {
      label: "药品名称",
      value: "commonName",
      type: "input",
    },
    { label: "药品编码", value: "code", type: "input" },
    {
      label: "状态",
      value: "status",
      type: "radio-model",
      code: "new_enabled_type",
    },
    {
      label: "规格",
      value: "standard",
      type: "input",
    },
    {
      label: '计量单位',
      value: 'unitId',
      type: 'select',
      required: true,
      list: 'unitList',
      filterable: true,
    },
    
    {
      label: '上架状态',
      value: 'putShelfStatus',
      type: 'radio-model',
      code: 'put_down_shelf',
    },
    // {
    //   label: "品牌",
    //   value: "trademark",
    //   type: "input",
    // },

    {
      label: "备注",
      value: "remark",
      type: "textarea",
    },
  ],
  spreadFieldList: [
    {
      label: "是否挂网",
      value: "isSunPurchase",
      type: "radio-model",
      code: "default_no_or_yes",
    },
    {
      label: '挂网类型',
      value: 'networkType',
      show: false,
      type: 'select-model',
      clearable: true,
      code: 'network_type',
      checkDefault: true,
    },
    {
      label: "挂网产品类型",
      value: "networkProductType",
      type: "slot",
      clearable: true,
      code: "network_product_type",
      checkDefault: true,
    },
    { label: "商品代码", value: "serialNum", type: "input" },
    { label: "挂网药品产品id", value: "procureCatalogId", type: "input" },
    {
      label: '挂网单位',
      value: 'networkUnit',
      show: false,
      type: 'input',
    },
    {
      label: '单位比例',
      value: 'networkUnitCoefficient',
      show: false,
      type: 'slot',
    },
    {
      label: '挂网单价',
      value: 'networkPrice',
      show: false,
      type: 'slot',
    },
  ],
  rules: {
    commonName: [
      { required: true, message: "请输入药品名称", trigger: "blur" },
    ],
    code: [{ required: true, message: "请输入药品编码", trigger: "blur" }],
    standard: [{ required: true, message: "请输入规格", trigger: "blur" }],
    unitId: [{ required: true, message: "请选择计量单位", trigger: "change" }],
    trademark: [{ required: true, message: "请输入品牌", trigger: "blur" }],
    networkType: [
      { required: true, message: "请选择挂网类型", trigger: "change" },
    ],
    networkProductType: [
      { required: true, message: "请选择挂网产品类型", trigger: "change" },
    ],
    serialNum: [
      { required: true, message: "请输入商品代码", trigger: "change" },
    ],
    networkUnit: [
      { required: true, message: "请输入挂网单位", trigger: "change" },
    ],
    networkUnitCoefficient: [
      { required: true, validator: checkFrequency, trigger: "change" },
    ],
    procureCatalogId: [
      { required: true, message: "请输入挂网耗材产品id", trigger: "change" },
    ],
  },
  labelWidth: "120px",
});

const listTypeInfo = ref({
  licenseList: [],
  brandList: [],
  unitList: [],
});

const networkProductTypeList = ref([])

const showDialog = computed({
  get() {
    return props.visible;
  },
  set(val) {
    // 更新父组件visible
    emits("update:visible", val);
  },
});
const unitvalue = computed(() => {
  let result = ''
  listTypeInfo.value.unitList.find((item) => {
    if (item.value === formInfo.value.data.unitId) {
      result = item.key
    }
  })
  return result
})
watch(
  () => formInfo.value.data.isSunPurchase,
  (value) => {
    if (value == 1) {
      showFieldListItem(true, 'networkType', 'spreadFieldList')
      showFieldListItem(true, "serialNum", "spreadFieldList");
      showFieldListItem(true, 'networkUnit', 'spreadFieldList')
      showFieldListItem(true, "networkUnitCoefficient", "spreadFieldList");
      showFieldListItem(true, "networkProductType", "spreadFieldList");
      showFieldListItem(true, "procureCatalogId", "spreadFieldList");
      showFieldListItem(true, 'networkPrice', 'spreadFieldList')
      formInfo.value.data["isSunPurchaseValue"] = "是";
    } else {
      showFieldListItem(false, 'networkType', 'spreadFieldList')
      showFieldListItem(false, "serialNum", "spreadFieldList");
      showFieldListItem(false, "networkUnitCoefficient", "spreadFieldList");
      showFieldListItem(false, "networkProductType", "spreadFieldList");
      showFieldListItem(false, "procureCatalogId", "spreadFieldList");
      showFieldListItem(false, 'networkPrice', 'spreadFieldList')
      showFieldListItem(false, 'networkUnit', 'spreadFieldList')
      formInfo.value.data['networkType'] = -2
      formInfo.value.data["serialNum"] = "";
      formInfo.value.data['systemUnitCoefficient'] = ''
      formInfo.value.data["networkUnitCoefficient"] = "";
      formInfo.value.data["networkProductType"] = "";
      formInfo.value.data['networkPrice'] = ''
      formInfo.value.data['networkUnit'] = ''
      formInfo.value.data["procureCatalogId"] = "";
      formInfo.value.data["isSunPurchaseValue"] = "否";
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(() => {
  getUnitList();
  let type = proxy.$store.state.permission.dict['network_product_type']
  networkProductTypeList.value = type.filter(item => item.code == 3)
  getStatus();
  if (props.id) {
    getDeatil();
    getList()
  }
});
function changePrice(e, str) {
  props.$refs.tableForm.clearValidate(str)
}
function setDefault(row) {
  if (props.id && !props.isCopy) {
    setSupplierProductDefault(row.id).then((res) => {
      if (res && res.success) {
        getList()
      }
    })
  }
}
function showFieldListItem(show, nameValue, str) {
  formInfo.value[str].forEach((item) => {
    if (nameValue === item.value) {
      item.show = show;
    }
  });
}
function remove(row) {
  if (row && row.supplierId) {
    if (props.id) {
      let ids = [row.id]
      reRemove(ids)
    } else {
      tableInfo.value.data = tableInfo.value.data.filter((item) => item !== row)
      if (tableInfo.value.data.length) {
        let itemList = tableInfo.value.data.filter(
          (item) => item.isDefault == 1
        )
        if (!itemList.length) {
          tableInfo.value.data[0].isDefault = 1
          tableInfo.value.data[0].isDefaultValue = '是'
        }
      }
    }
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        if (props.id) {
          let ids = tableInfo.value.selections.map((item) => item.id)
          reRemove(ids)
        } else {
          tableInfo.value.data = tableInfo.value.data.filter(
            (item) => !tableInfo.value.selections.includes(item)
          )
          if (tableInfo.value.data.length) {
            let itemList = tableInfo.value.data.filter(
              (item) => item.isDefault == 1
            )
            if (!itemList.length) {
              tableInfo.value.data[0].isDefault = 1
              tableInfo.value.data[0].isDefaultValue = '是'
            }
          }
        }
      })
  }
}
function reRemove(ids) {
  productsRelationSupplierDel(ids, props.id).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function showSupplier(row) {
  // proxy.$router.push({
  //   name: 'supplier',
  //   params: {
  //     supplierId: row.supplierId,
  //   },
  // })
}
function addSuppler() {
  supplierInfo.value.visible = true
  let ids = tableInfo.value.data.map((item) => item.supplierId)
  supplierInfo.value.query.supplierIdNotIn = ids.length ? ids.toString() : ''
}
function supplierCallback(data) {
  if (data && data.length) {
    let arr = data.map((item) => {
      return {
        price: item.price || 0,
        supplierName: item.supplierName,
        supplierCode: item.supplierCode,
        supplierId: item.supplierId,
        contact: item.contact,
        contactNumber: item.contactNumber,
        expectDeliveryDay: item.expectDeliveryDay,
        isDefault: 0,
        isDefaultValue: '否',
      }
    })
    if (props.id) {
      let params = {
        id: props.id,
        supplierList: arr,
      }
      productsRelationSupplier(params).then((res) => {
        if (res && res.success) {
          getList()
        }
      })
    } else {
      tableInfo.value.data = arr.concat(tableInfo.value.data)
      let itemList = tableInfo.value.data.filter((item) => item.isDefault == 1)
      if (!itemList.length) {
        tableInfo.value.data[0].isDefault = 1
        tableInfo.value.data[0].isDefaultValue = '是'
      }
    }
  }
}
function getList() {
  getSupplierProductAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      let data = res.data
      if (data && data.length) {
        data.forEach((item) => {
          item.isDefault = item.isDefault ? item.isDefault : 0
          item.isDefaultValue = item.isDefault ? item.isDefaultValue : '否'
        })
      }
      tableInfo.value.data = data
    }
  })
}

const getDeatil = () => {
  getDrugById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data;
      formInfo.value.data.networkProductType = resp.data.networkProductType + ''
      formInfo.value.data.unitId = resp.data.unitId == -2 ? '' : resp.data.unitId
      formInfo.value.data.putShelfStatus = resp.data.putShelfStatus == -2 ? '' : resp.data.putShelfStatus
      formInfo.value.data.networkType = !resp.data.networkType ? '' : resp.data.networkType
    }
  });
};
const save = async () => {
  let formRef = [
    formInfo.value.ref,
    formInfo.value.spreadRef,
  ]
  proxy.$fn.checkForm(formRef).then(() => {
    const requestData = formInfo.value.data;
    if (props.id) {
      requestData.id = props.id;
    }
    const api = updateDrug;
    console.log(api);
    api(requestData).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false;
        emits("returnModify");
        formInfo.value.ref.validateField();
      }
    });
  })

};

//获取计量单位列表
const getUnitList = () => {
  getUnitAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.value.unitList = resp.data.map(function (item) {
        return { key: item.name, value: item.id };
      });
    }
  });
};
const getStatus = () => {
  getCoreCodeStatus({ codeType: "9" }).then((res) => {
    showFieldListItem(!res.data, "code");
    formInfo.value.rules.code[1].required = !res.data;
  });
};
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 200px;
  z-index: 12;
}

.inputScan {
  ime-mode: disabled;
}

.active {
  display: none;
}
</style>
